package com.ttmall.rest.service.impl;

import com.ttmall.common.pojo.CategoryNode;
import com.ttmall.common.pojo.ItemCatResult;
import com.ttmall.mapper.TbItemCatMapper;
import com.ttmall.pojo.TbItemCat;
import com.ttmall.pojo.TbItemCatExample;
import com.ttmall.pojo.TbItemParamExample;
import com.ttmall.rest.service.ItemCatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * ItemCatService的service层
 * Created by GalaIO on 2018/1/16.
 */
@Service
public class ItemCatServiceImpl implements ItemCatService {

    @Autowired
    private TbItemCatMapper tbItemCatMapper;

    @Override
    public ItemCatResult listItemCat() {
        return ItemCatResult.build(listItemCatChildren(0L, 14));
    }


    private List<?> listItemCatChildren(long parentId, int maxCount) {
        List<Object> result = new ArrayList<>();
        TbItemCatExample example = new TbItemCatExample();
        TbItemCatExample.Criteria criteria = example.createCriteria();
        criteria.andParentIdEqualTo(parentId);
        List<TbItemCat> queryResult = tbItemCatMapper.selectByExample(example);
        for (TbItemCat tbItemCat : queryResult) {
            if (result.size() > maxCount) {
                break;
            }
            if (tbItemCat.getIsParent()) {
                CategoryNode node = new CategoryNode();
                node.setName(CategoryNode.buildName(tbItemCat.getId(), tbItemCat.getName()));
                node.setUrl(CategoryNode.buildUrl(tbItemCat.getId()));
                node.setItems(listItemCatChildren(tbItemCat.getId(), maxCount));
                result.add(node);
            } else {
                result.add(CategoryNode.buildUrlName(tbItemCat.getId(), tbItemCat.getName()));
            }
        }
        return result;
    }

}
